var hx = require("hbuilderx");
var fs = require('fs')
var {
	othersSetDataPath
} = require('../options.js')

function createFile(filePath, data = {}) {
	fs.writeFileSync(filePath, JSON.stringify(data, null, '\t'), 'utf-8');
}

// 命令：othersSet
module.exports = async function() {
	const appRoot = hx.env.appRoot
	const activeEditor = await hx.window.getActiveTextEditor();
	// const projectName = activeEditor.document.workspaceFolder.name
	const uniAppId = (await hx.util.readJSONValue(
		`${activeEditor.document.workspaceFolder.uri.path.replace(/^\//, '')}/manifest.json`, 'appid')).data
	// 表单数据
	const formItems = [
		{
			"type": "radioGroup",
			"name": "autoUpload",
			"label": "打包完成自动上传服务器: ",
			"items": [{
					"label": "是",
					"id": "yes"
				},
				{
					"label": "否",
					"id": "no"
				}
			],
			"value": "yes"
		}, {
			"type": "radioGroup",
			"name": "coverOldFile",
			"label": "上传服务器可覆盖原文件: ",
			"items": [{
					"label": "是",
					"id": "yes"
				},
				{
					"label": "否",
					"id": "no"
				}
			],
			"value": "yes"
		}

	]
	// 默认的表单-value数据
	let initFormData = formItems.reduce((p, c) => {
		p[c.name] = ""
		return p
	}, {})

	// 获取已保存的表单-value数据
	const savedData = await hx.util.readJSONValue(othersSetDataPath, uniAppId)
	if (savedData.code == '-1') {
		createFile(othersSetDataPath)
	} else if (savedData.data) {
		initFormData = savedData.data
	}

	console.log('initFormData', initFormData);

	hx.window.showFormDialog({
		formItems: formItems.map(i => {
			if (initFormData[i.name]) {
				i.value = initFormData[i.name]
			}
			return i
		}),
		title: "其他设置",
		width: 480,
		height: 200,
		submitButtonText: "提交(&S)",
		cancelButtonText: "取消(&C)",
		validate: function(formData) {
			return formItems.every(i => {
				if (i.required && !formData[i.name]) {
					this.showError(i.placeholder);
					return false
				}
				return true
			})
		},
	}).then((res) => {
		hx.util.writeJSONValue(othersSetDataPath, uniAppId, res);
	});
}